package com.agnes.okhttp.lib.callback;

import android.app.Activity;

import com.google.gson.Gson;
import com.agnes.okhttp.lib.NetConst;
import com.agnes.okhttp.lib.entity.standard.CommonEntity;
import com.agnes.okhttp.lib.util.GsonRespParser;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


public abstract class EntityCallback<T> extends QkBaseCallback {

    private Class mClazz;

    public EntityCallback(Activity context) {
        this(context, true);
    }

    public EntityCallback(Activity context, boolean showLoading) {
        super(context, showLoading);
        Type genType = getClass().getGenericSuperclass();
        if (genType != null) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            mClazz = (Class) params[0];
        }
    }


    @Override
    protected int emptyFlag() {
        return NetConst.FLAG_JO;
    }

    @Override
    protected void parseResult(JSONObject rootJson) {
        CommonEntity<T> entity = parseJsonObject(rootJson);
        if (entity != null) {
            if (NetConst.SUCCESS_CODE == entity.getCode()) {
                onSuccess(entity.getMessage(), entity.getData());
            } else {
                onFail(entity.getCode(), entity.getMessage(), entity.getData());
            }
        } else {
            onFail(NetConst.CODE_PARSE_NULL, "解析错误", null);
        }
    }


    /**
     * 开发者调用
     *
     * @param msg  提示信息
     * @param data data
     */
    public abstract void onSuccess(String msg, T data);

    /**
     * 开发者重写
     *
     * @param code       0 以外的错误码
     * @param failureMsg 错误信息
     * @param data       data
     */
    public void onFail(int code, String failureMsg, T data) {
        // 如需处理异常code,需重写该方法
    }


    private CommonEntity<T> parseJsonObject(JSONObject response) {
        CommonEntity<T> entity = null;
        if (mClazz != null) {
            Type gsonType = new GsonRespParser(CommonEntity.class, new Class[]{mClazz});
            try {
                entity = new Gson().fromJson(response.toString(), gsonType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return entity;
    }


}
